import { game, RenderRoot2D } from 'cc'
import Singleton from '../Base/Singleton'
import { DEFAULT_DURATION, DrawManager } from '../Scripts/UI/DrawManager'
import { createUINode } from '../Utils'

export default class FaderManager extends Singleton {
  static get Instance() {
    return super.GetInstance<FaderManager>()
  }

  private _fader: DrawManager = null

  get fader(): DrawManager {
    if (this._fader !== null) {
      return this._fader
    }

    const root = createUINode()
    root.addComponent(RenderRoot2D)

    const fadeNode = createUINode()
    fadeNode.setParent(root)
    this._fader = fadeNode.addComponent(DrawManager)
    this._fader.init()
    game.addPersistRootNode(root) // 通过常驻节点进行场景资源管理和参数传递: https://docs.cocos.com/creator/3.8/manual/zh/scripting/scene-managing.html#%E9%80%9A%E8%BF%87%E5%B8%B8%E9%A9%BB%E8%8A%82%E7%82%B9%E8%BF%9B%E8%A1%8C%E5%9C%BA%E6%99%AF%E8%B5%84%E6%BA%90%E7%AE%A1%E7%90%86%E5%92%8C%E5%8F%82%E6%95%B0%E4%BC%A0%E9%80%92

    return this._fader
  }

  async fadeIn(duration: number = DEFAULT_DURATION) {
    await this.fader.fadeIn(duration)
  }

  async fadeOut(duration: number = DEFAULT_DURATION) {
    await this.fader.fadeOut(duration)
  }

  async mask() {
    await this.fader.mask()
  }

}
